import { message } from '@common/assets/js/resetMessage';
import utils from "@common/utils/utils";
import common from "@common/api/common";
import constants from "@common/api/constants";
import GlobalDialog from "@common/components/dialog/global";
import Preview from "./Preview";

const getDesignData = async sid => {
	const callback = () => {
	};
	let result = await common.requestData(constants.API_GetBasePrintDesignBySid, { sid }, callback, callback, callback);
	if (result.code !== 0) {
		message.error('获取模板失败：' + result.message);
		return;
	}
	let resultData = result.data || {};
	if (!utils.isNotEmpty(resultData.template_json)) {
		message.error('请先设计模板');
		return;
	}
	let templateJson = {};
	try {
		templateJson = JSON.parse(resultData.template_json);
	} catch (e) {
		message.error('请先设计模板');
		return;
	}
	if (!utils.isNotEmptyList(templateJson.panels)) {
		message.error('请先设计模板');
		return;
	}
	return templateJson;
};
const genButtons = () => {
	let buttons = [];
	buttons.push({
		text: '关 闭',
		click(dialog) {
			dialog.visible = false;
		},
	});
	buttons.push({
		type: 'primary',
		text: '转PDF',
		click(dialog, { component }) {
			component && typeof component.toPdf === 'function' && component.toPdf();
		},
	});
	buttons.push({
		type: 'primary',
		text: '打印',
		click(dialog, { component }) {
			component && typeof component.doPrint === 'function' && component.doPrint();
		}
	});
	return buttons;
};
const PrintPreview = (store, router) => {
	let dialog = GlobalDialog(store, router);
	return async options => {
		let template = options.template;
		if (!options.preview) {
			template = await getDesignData(options.template);
			if (!template) {
				return;
			}
		}
		let width = 'calc(210mm + 54px)';
		if (utils.isNotEmptyList(template.panels)) {
			let panelIndex = 0;
			if (utils.isNotEmpty(options.panelIndex)) {
				panelIndex = options.panelIndex;
			}
			let panelData = template.panels[panelIndex];
			if (panelData.width > 297) {
				width = '60%';
			} else {
				width = `calc(${ panelData.width }mm + 54px)`;
			}
		}
		const dialogVm = dialog({
			title: options.title || '打印预览',
			width,
			component: {
				value: Preview,
				props: {
					template,
					data: options.data,
					fetch: options.fetch,
					panelIndex: options.panelIndex,
					pageSize: options.pageSize,
					preview: options.preview,
				},
				event(event) {
					if (typeof options.event === 'function') {
						options.event(event, dialogVm);
					}
				},
			},
			buttons: genButtons(),
		});
		return dialogVm;
	};
};
export default PrintPreview;